package com.lvmama.pangolin.timer.processor;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.busi.timer.TimerManager;
import com.lvmama.pangolin.busi.timer.TimerManagerAssist;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.JobConfig;
import com.lvmama.pangolin.entity.TaskSequence;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.service.JobConfigService;
import com.lvmama.pangolin.service.TaskSequenceService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.SpringContextUtil;

public class TimerGenerator extends CommonJob {

	@Autowired
	private JobConfigService jobConfigService;
	@Autowired
	private TimerService timerService;
	@Autowired
	private TaskSequenceService taskSequenceService;
	
	
	private Logger logger = Logger.getLogger(TimerGenerator.class);
	@Override
	public void runJob(JobExecutionContext context, String parameter) 
	{
		logger.info("TimerGenerator:生成任务开始！");
		String jobCode  = (String)context.getJobDetail().getJobDataMap()
							.get(TimerManager.JOB_CODE);
		
		String syscode=System.getProperties().getProperty("SYSCODE");
		syscode = StringTools.isValid(syscode)?syscode:"PUBLIC";
		
		if(timerService == null)
		{
			timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
		}
		Map<String,Object> timerParam = new HashMap<String,Object>();
		timerParam.put("job_code", jobCode);
		timerParam.put("job_type", "1");
		timerParam.put("timer_valid", "1");
		timerParam.put("syscode", syscode);
		List<String> statusList = new ArrayList<String>();
		statusList.add("0");
		statusList.add("1");
		statusList.add("2");
		statusList.add("3");
		timerParam.put("timer_status", statusList);
		List<Timer> timerL = timerService.queryTimerGroupByTaskId(timerParam);
		boolean lastTaskComplete = true;
		if(timerL != null && !timerL.isEmpty())
		{
			if(timerL.get(0).getGroup_count() > 0)
			{
				lastTaskComplete = false;
			}
			
		}
		if(lastTaskComplete)
		{
			generatorTimer(jobCode,syscode);
		}
		else
		{
			delayTimer(context);
		}
		logger.info("TimerGenerator:生成任务结束！");
		

	}
	
	private void delayTimer(JobExecutionContext context)
	{
		logger.info("上次同类型任务未完成，请检查处理！");
	}
	
	private void generatorTimer(String jobCode,String syscode)
	{
		Map<String,String> param = new HashMap<String,String>();
		param.put("job_code", jobCode);
		param.put("job_type", "1");
		param.put("job_valid", "1");
		param.put("syscode", syscode);
		
		if(jobConfigService == null)
		{
			jobConfigService = (JobConfigService) SpringContextUtil.getBean(JobConfigService.class);
		}
		if(taskSequenceService == null)
		{
			taskSequenceService = (TaskSequenceService) SpringContextUtil.getBean(TaskSequenceService.class);
		}
		List<JobConfig> jobconfigs = jobConfigService.queryJobconfig(param);
		List<Timer> timerList = new ArrayList<Timer>();
		if(jobconfigs != null && !jobconfigs.isEmpty())
		{
			Timer tv = null;
			int sequenceId = 0;
			try
			{
				TaskSequence taskSequence = new TaskSequence();
				taskSequenceService.insertTaskSeqence(taskSequence);
				sequenceId = taskSequence.getId();
			}
			catch (Exception e)
			{
			}
			String task_id = StringTools.addSingleStr(String.valueOf(sequenceId),"0",8,true);
			for (JobConfig jobConfigVO : jobconfigs)
			{
				tv = createTimer(jobConfigVO,task_id);
				timerList.add(tv);
			}
			
		}
		TimerManagerAssist timerAssist = new TimerManagerAssist();
		if(!timerList.isEmpty())
		{
			
			for (Timer timerVO : timerList)
			{
				
				timerVO.setTask_timer_count(timerList.size());
			}
			timerService.insertTimerList(timerList);
			
			for (Timer timerVO : timerList)
			{
				try
				{
					timerAssist.loadValidJob(timerVO);
				}catch(Exception e)
				{
					logger.debug("刷新timer失败！");
				}
				
			}
			
		}
		
	}
	
	private Timer createTimer(JobConfig jobConfigVO,String batch_num)
	{
		Timer tv = new Timer();
		tv.setSyscode(jobConfigVO.getSyscode());
		tv.setTimer_id(StringTools.getTimerSeq("yyyyMMddHHmmssSSS",true,4));
		tv.setJob_code(jobConfigVO.getJob_code());
		tv.setJob_type(jobConfigVO.getJob_type());
		tv.setTask_id(batch_num);
		tv.setTimer_code(jobConfigVO.getSub_job_code());
		tv.setTimer_seq(jobConfigVO.getJob_seq());
		tv.setTimer_name(jobConfigVO.getJob_name());
		tv.setExec_mode(jobConfigVO.getExec_mode());
		tv.setTimer_classname(jobConfigVO.getJob_classname());
		tv.setTimer_param(jobConfigVO.getJob_param());
		tv.setTimer_cron(jobConfigVO.getJob_cron());
		tv.setTimer_valid(1);
		tv.setTimer_status("0");
		tv.setRetry_num(jobConfigVO.getRetry_num());
		tv.setRun_num(0);
		tv.setCreate_time(new Date());
		tv.setTimer_granularity(jobConfigVO.getJob_granularity());
//		tv.setGranularity_value("3");
		tv.setConvert_retry_num(jobConfigVO.getConvert_retry_num());
		tv.setConvert_run_num(0);
		return tv;
		
	}

}
